//
// 业务处理器，管理队列和处理逻辑
// 接收到的数据包先放队列里，再慢慢消费
// Created by kenny on 25-10-30.
//
#include "mcp_recv_mgr.h"
#include "mcp_logger.h"
#include <stdlib.h>
#include <mcp_decode.h>
#include <stdio.h>

#ifdef _WIN32
    #include <windows.h>
#else
    #include <pthread.h>
    #include <unistd.h>
#endif

// 处理器结构体定义
struct packet_processor_t {
    mcp_queue_t* queue;        // 数据包队列
    int is_processing;           // 处理任务是否运行
    packet_callback_t callback;  // 回调函数指针
#ifdef _WIN32
    CRITICAL_SECTION lock;       // Windows临界区
#else
    pthread_mutex_t lock;        // Linux/Unix互斥锁
#endif
};

// 前向声明处理函数
static void process_task(const packet_processor_t* processor, CustomPacket packet);
static void process_queue_loop(packet_processor_t* processor);

// 队列数据包的复制和销毁
void* packet_copy(void* dest, const void* src, size_t element_size) {
    printf("element_size: %p\n", &element_size);
    const CustomPacket* src_packet = (const CustomPacket*)src;
    CustomPacket* dest_packet = (CustomPacket*)dest;

    // 复制基本字段
    *dest_packet = *src_packet;  // 直接结构体赋值

    // 深度拷贝data字段
    if (src_packet->data && src_packet->data_length > 0) {
        dest_packet->data = malloc(src_packet->data_length);
        memcpy(dest_packet->data, src_packet->data, src_packet->data_length);
    } else {
        dest_packet->data = NULL;
        dest_packet->data_length = 0;
    }

    return dest;
}
void packet_free(void* element) {
    CustomPacket* packet = (CustomPacket*)element;
    if (packet->data) {
        free(packet->data);
        packet->data = NULL;
    }
    packet->data_length = 0;
}

/**
 * 创建处理器
 */
packet_processor_t* packet_processor_create(int queue_capacity, packet_callback_t callback) {
    packet_processor_t* processor = (packet_processor_t*)malloc(sizeof(packet_processor_t));
    if (!processor) {
        LOG_ERROR("Failed to allocate memory for packet processor");
        return NULL;
    }

    processor->queue = mcp_queue_create(queue_capacity,sizeof(CustomPacket),packet_copy,packet_free);
    if (!processor->queue) {
        LOG_ERROR("Failed to create packet queue");
        free(processor);
        return NULL;
    }

    processor->is_processing = 0;
    processor->callback = callback;  // 保存回调函数

#ifdef _WIN32
    InitializeCriticalSection(&processor->lock);
#else
    if (pthread_mutex_init(&processor->lock, NULL) != 0) {
        LOG_ERROR("Failed to initialize processor mutex");
        packet_queue_destroy(processor->queue);
        free(processor);
        return NULL;
    }
#endif

    LOG_INFO("Packet processor created with queue capacity: %d", queue_capacity);
    return processor;
}

/**
 * 销毁处理器
 */
void packet_processor_destroy(packet_processor_t* processor) {
    if (!processor) {
    }

    // 停止处理
    packet_processor_stop(processor);

    // 销毁队列
   mcp_queue_destroy(processor->queue);

#ifdef _WIN32
    DeleteCriticalSection(&processor->lock);
#else
    pthread_mutex_destroy(&processor->lock);
#endif

    free(processor);
    LOG_INFO("Packet processor destroyed");
}

/**
 * 启动处理
 */
void packet_processor_start(packet_processor_t* processor) {
    if (!processor) {
        return;
    }

#ifdef _WIN32
    EnterCriticalSection(&processor->lock);
#else
    pthread_mutex_lock(&processor->lock);
#endif

    if (!processor->is_processing && !mcp_queue_is_empty(processor->queue)) {
        processor->is_processing = 1;
        LOG_DEBUG("Starting packet processing");
        // 在实际项目中，这里可以启动一个处理线程
        // 但按照你的需求，我们在主循环中处理

        process_queue_loop(processor);
    }

#ifdef _WIN32
    LeaveCriticalSection(&processor->lock);
#else
    pthread_mutex_unlock(&processor->lock);
#endif
}

/**
 * 停止处理
 */
void packet_processor_stop(packet_processor_t* processor) {
    if (!processor) {
        return;
    }

#ifdef _WIN32
    EnterCriticalSection(&processor->lock);
#else
    pthread_mutex_lock(&processor->lock);
#endif

    processor->is_processing = 0;

#ifdef _WIN32
    LeaveCriticalSection(&processor->lock);
#else
    pthread_mutex_unlock(&processor->lock);
#endif

    LOG_DEBUG("Packet processing stopped");
}

/**
 * 添加数据包到处理器
 */
int packet_processor_add_packet(packet_processor_t* processor, const CustomPacket* packet) {
    if (!processor || !packet) {
        LOG_ERROR("Invalid processor or packet");
        return -1;
    }

    int result = mcp_queue_enqueue(processor->queue, packet);
    if (result == 0) {
        // 成功添加数据包后，尝试启动处理
        packet_processor_start(processor);
    }

    return result;
}

/**
 * 检查处理器是否正在运行
 */
int packet_processor_is_running(const packet_processor_t* processor) {
    if (!processor) {
        return 0;
    }
    return processor->is_processing;
}

/**
 * 处理队列循环（在主线程中调用）
 */
void process_queue_loop(packet_processor_t* processor) {
    if (!processor) {
        return;
    }

    while (1) {
        CustomPacket packet;

        // 从队列取出数据包
        if (mcp_queue_dequeue(processor->queue, &packet) != 0) {
            // 队列为空，停止处理任务
#ifdef _WIN32
            EnterCriticalSection(&processor->lock);
#else
            pthread_mutex_lock(&processor->lock);
#endif

            processor->is_processing = 0;

#ifdef _WIN32
            LeaveCriticalSection(&processor->lock);
#else
            pthread_mutex_unlock(&processor->lock);
#endif

            LOG_DEBUG("Packet queue empty, stopping processing");
            break;
        }

        // 处理数据包
        LOG_DEBUG("Processing packet from queue, protocol: 0x%02X", packet.protocol);
        process_task(processor,packet);

        // 短暂休眠，避免过度占用CPU
#ifdef _WIN32
        Sleep(10);
#else
        usleep(10000); // 10ms
#endif
    }
}

/**
 * 业务处理方法（需要从mcp_service.c中移过来）
 */
static void process_task(const packet_processor_t* processor, CustomPacket packet) {

    // 这里放置你的业务处理逻辑
    // 注意：这个函数需要从原来的mcp_service.c中移动过来
    // 为了保持完整性，这里先留空，实际使用时需要将原来的process_task实现移到这里
    // 解析数据内容
    uint8_t encrypt;
    uint8_t resp_protocol;
    uint16_t resp_sequence;
    char* message;

    // 解析数据包
    int ret = parse_packet_data(packet.data, packet.data_length, &encrypt, &resp_protocol, &resp_sequence, &message);
    // LOG_DEBUG("数据包解码结果: %d\n", ret);
    if (ret == 0) {
        LOG_DEBUG("<<<<<< Packet Header: encrypt=%d, resp_protocol=0x%02X, resp_sequence=%d, message=%s\n",
               encrypt, resp_protocol, resp_sequence, message);
        // 从这里返回给 应用层的 APP
        // 执行回调函数，将message传递给应用层
        if (processor->callback && message) {
            processor->callback(message, resp_protocol, resp_sequence);
        }
    }else {
        LOG_ERROR("<<<<<< Packet decoding error: %d\n", ret);
    }
    free(message);
    free_packet(&packet);
}